<template>
    <view>
        <!-- <custom-header title="个人信息" /> -->
        <view class="container">
            <form @submit="formSubmit">
                <!-- 头像上传 -->
                <view class="form-item avatar-item">
                    <text class="label">头像</text>
                    <view class="avatar-wrapper" >
						<image class="avatar" :src="userInfo.userImage || defaultAvatar" mode="aspectFill" />
                        <button class="upload-mask" open-type="chooseAvatar" @chooseavatar="chooseAvatar" >
							上传
                        </button>
                        <!-- <image class="avatar" :src="userInfo.image || defaultAvatar" mode="aspectFill" />
                        <view class="upload-mask">点击上传</view> -->
                    </view>
                </view>

                <!-- 昵称输入 -->
                <view class="form-item">
                    <text class="label">昵称</text>
                    <input name="nickname" type="nickname" class="input"  placeholder="请输入昵称" v-model="userInfo.nickname" placeholder-class="placeholder" />
                </view>

                <!-- 生日选择 -->
                <view class="form-item">
                    <text class="label">生日</text>
                    <picker :disabled="isBirthdayLocked" v-if="!userInfo.birthDate" mode="date" name="birthday" start="1970-01-01" :end="currentDate" @change="bindDateChange">
                        <view :class="'picker ' + (isBirthdayLocked ? 'disabled' : '')">
                            {{ userInfo.birthDate || '请选择生日' }}
                        </view>
                    </picker>
                    <view v-else>
                        <view class="picker disabled">{{ userInfo.birthDate?.substring(0, 10) }}</view>
                    </view>
                </view>

                <!-- 提示文字 -->
                <view class="tip">生日填写后不可修改，次年即可领取丰厚权益</view>

                <!-- 保存按钮 -->
                <view class="submit-btn" @tap="updateInfo">保存</view>
            </form>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { uploadApi } from '@/api/file/index'
import { updateUserInfo } from '@/api/user/index'
import { getUserInfo,setUserInfo } from '@/utils/user'
// 响应式数据
const defaultAvatar = ref('/static/images/login_image.png')
const avatarUrl = ref('')
const nickname = ref('打球人')
const birthday = ref('')
const currentDate = ref('2003-12-31')
const isBirthdayLocked = ref(false)
const formValid = ref(false)
const userInfo = ref({
    avatarUrl: '',
    nickname: '',
    birthDate: ''
})

// 页面加载
onLoad( async (options) => {
    let res = await getUserInfo()
    userInfo.value = res.result
    if (userInfo.value.birthDate) {
        isBirthdayLocked.value = true
    }
	console.log('111',userInfo.value);
})

// 选择头像
const chooseAvatar = async (e) => {
    console.log(e,'chooseAvatar');
    //上传图片
    const res = await uploadApi(e.detail.avatarUrl)
	userInfo.value.userImage = res.message
    console.log('文件上传地址',userInfo.value.avatarUrl)
}



// 更新用户信息
const updateInfo = async () => {
    // 将日期字符串转换为时间戳，Java的Date类型可以直接解析时间戳
    let birthDateFormatted = null
    if (userInfo.value.birthDate) {
        // 创建Date对象并获取时间戳（毫秒）
        const date = new Date(userInfo.value.birthDate + 'T00:00:00')
        birthDateFormatted = date.getTime()
    }
     
    let params = {
        userId: userInfo.value.userId,
        nickName: userInfo.value.nickname,
        avatarUrl: userInfo.value.userImage,
        birthDate: birthDateFormatted
    }
    const res = await updateUserInfo(params) 
    if (res.code === 200) {
        uni.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 1000)
    }
	// userInfo.value = res.
	
    // WXCall.WXCall('/wx/app/user/edit', params, 'POST', true, (res) => {
    //     if (res.code >= 0) {
    //         console.log(res);
    //     } else {
    //         new Error(res.ReturnInfo);
    //     }
    // });
}

// 日期选择
const bindDateChange = (e) => {
    if (!isBirthdayLocked.value) {
        userInfo.value.birthDate = e.detail.value
        checkFormValid()
    }
}

// 表单验证
const checkFormValid = () => {
    const valid = nickname.value.trim().length > 0 && birthday.value !== '' && avatarUrl.value !== ''
    formValid.value = valid
}

// 表单提交
const formSubmit = (e) => {
    if (formValid.value) {
        isBirthdayLocked.value = true
        uni.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
        })
        // 这里可添加上传头像到服务器的逻辑
        // wx.uploadFile({...})
    }
}
</script>

<style>
.container {
    padding: 30rpx;
    /* margin-top: 160rpx; */
}

.form-item {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1rpx solid #eee;
}

.label {
    width: 150rpx;
    font-size: 32rpx;
    color: #333;
}

.input,
.picker {
    flex: 1;
    font-size: 32rpx;
    color: #333;
}

.placeholder {
    color: #ccc;
}

.disabled {
    color: #999 !important;
}

.tip {
    margin: 30rpx 0;
    color: #999;
    font-size: 26rpx;
}

.submit-btn {
    margin-top: 60rpx;
    background: #001c71;
    color: white;
    border-radius: 50rpx;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
}

.button-hover {
    opacity: 0.9;
}

.avatar-item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    height: 160rpx !important;
}

.avatar-wrapper {
    position: relative;
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    overflow: hidden;
}

.avatar {
    width: 100%;
    height: 100%;
    background-color: #f0f0f0;
}

.upload-mask {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 40rpx;
    line-height: 40rpx;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    font-size: 24rpx;
    text-align: center;
}
</style>
